package com.jzr.bedside.service.nettyUtils

import android.os.Build
import com.blankj.utilcode.utils.EmptyUtils
import com.jzr.bedside.base.BaseApplication
import com.jzr.bedside.utils.CommonUtil
import com.jzr.bedside.utils.PreferUtil
import com.jzr.netty.common.protocol.PingMsg
import com.orhanobut.logger.Logger
import io.netty.bootstrap.Bootstrap
import io.netty.channel.*
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioSocketChannel
import io.netty.handler.codec.serialization.ClassResolvers
import io.netty.handler.codec.serialization.ObjectDecoder
import io.netty.handler.codec.serialization.ObjectEncoder
import io.netty.handler.timeout.IdleStateHandler
import java.util.concurrent.TimeUnit

object NettyClient {


    var isConnect = false

    private var group: EventLoopGroup? = null
    private var bootstrap: Bootstrap? = null
    private var channelFuture: ChannelFuture? = null
    private var channel: Channel? = null

    fun connect() {
        if (!isConnect) {
            try {
                group = NioEventLoopGroup()
                bootstrap = Bootstrap().group(group)
                    .option(ChannelOption.SO_KEEPALIVE, true)
                    .channel(NioSocketChannel::class.java) //					.handler(new NettyClientInitializer(listener));
                    .handler(object : ChannelInitializer<SocketChannel>() {
                        @Throws(Exception::class)
                        override fun initChannel(ch: SocketChannel) {
                            ch.pipeline().addLast(IdleStateHandler(20, 10, 0))
                            ch.pipeline().addLast(ObjectEncoder())
                            ch.pipeline().addLast(ObjectDecoder(ClassResolvers.cacheDisabled(null)))
                            ch.pipeline().addLast(NettyClientHandler())
                        }
                    })
                channelFuture = bootstrap?.connect(
                    "192.168.41.2",
                    8060
                )?.addListener(ChannelFutureListener { channelFuture ->
                    if (channelFuture.isSuccess) {
                        Logger.e("socket 连接成功")
                        isConnect = true
                        channel = channelFuture.channel()

                    } else {
                        Logger.e("socket 连接失败")
                        isConnect = false
                    }
                })?.sync()
            } catch (e: Exception) {
                Logger.e(e.toString())
//                listener.onServiceStatusConnectChanged(NettyListener.STATUS_CONNECT_ERROR)
//                reconnect()
            }
        }
    }


    fun disconnect() {
        try {
            if (null != channelFuture) {
                if (channelFuture!!.channel() != null && channelFuture!!.channel().isOpen) {
                    channelFuture!!.channel().close()
                }
            }
            if (EmptyUtils.isNotEmpty(group)) group!!.shutdownGracefully()
            if (bootstrap != null) {
                bootstrap = null
            }
            if (channel != null) {
                channel = null
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
//        NettyService.destroyThread()
    }


    fun sendMsgToServer(data: Any?, listener: ChannelFutureListener?): Boolean {
        val flag = channel != null && isConnect
        if (flag) {
            channel?.writeAndFlush(data)?.addListener(listener)
        }
        return flag
    }


}